<template>
  <div class="auth-modal" v-if="show">
    <div class="modal-overlay" @click="close"></div>
    <div class="modal-content">
      <div class="modal-header">
        <div class="tabs">
          <div 
            class="tab" 
            :class="{ active: activeTab === 'login' }" 
            @click="activeTab = 'login'"
          >登录</div>
          <div 
            class="tab" 
            :class="{ active: activeTab === 'register' }" 
            @click="activeTab = 'register'"
          >注册</div>
        </div>
        <button class="close-btn" @click="close">×</button>
      </div>
      
      <!-- 登录表单 -->
      <div v-if="activeTab === 'login'" class="tab-content">
        <form @submit.prevent="handleLogin">
          <div class="form-group">
            <label>邮箱地址</label>
            <input v-model="loginForm.email" type="email" required placeholder="请输入邮箱地址" oninvalid="this.setCustomValidity('请输入有效的邮箱地址')" oninput="this.setCustomValidity('')" />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input v-model="loginForm.password" type="password" required placeholder="请输入密码" oninvalid="this.setCustomValidity('请输入密码')" oninput="this.setCustomValidity('')" />
          </div>
          <div v-if="loginForm.error" class="error-message">{{ loginForm.error }}</div>
          <button type="submit" class="submit-btn" :disabled="loginForm.loading">
            {{ loginForm.loading ? '登录中...' : '登录' }}
          </button>
        </form>
      </div>
      
      <!-- 注册表单 -->
      <div v-if="activeTab === 'register'" class="tab-content">
        <form @submit.prevent="handleRegister">
          <div class="form-group">
            <label>邮箱地址</label>
            <input v-model="registerForm.email" type="email" required placeholder="请输入邮箱地址" oninvalid="this.setCustomValidity('请输入有效的邮箱地址')" oninput="this.setCustomValidity('')" />
          </div>
          <div class="form-group">
            <label>密码</label>
            <input v-model="registerForm.password" type="password" required placeholder="请输入密码" oninvalid="this.setCustomValidity('请输入密码')" oninput="this.setCustomValidity('')" />
          </div>
          <div class="form-group">
            <label>确认密码</label>
            <input v-model="registerForm.confirmPassword" type="password" required placeholder="请再次输入密码" oninvalid="this.setCustomValidity('请再次输入密码')" oninput="this.setCustomValidity('')" />
          </div>
          <div class="form-group">
            <label>昵称</label>
            <input v-model="registerForm.nickname" type="text" required placeholder="请输入昵称" oninvalid="this.setCustomValidity('请输入昵称')" oninput="this.setCustomValidity('')" />
          </div>
          <div class="form-group verification-code">
            <label>验证码</label>
            <div class="code-input-container">
              <input v-model="registerForm.verificationCode" type="text" required placeholder="请输入验证码" oninvalid="this.setCustomValidity('请输入验证码')" oninput="this.setCustomValidity('')" />
              <button 
                type="button" 
                class="send-code-btn" 
                @click="sendVerificationCode"
                :disabled="registerForm.codeSent"
              >
                {{ registerForm.codeSent ? `重新发送(${registerForm.countdown}s)` : '发送验证码' }}
              </button>
            </div>
          </div>
          <div v-if="registerForm.error" class="error-message">{{ registerForm.error }}</div>
          <button type="submit" class="submit-btn" :disabled="registerForm.loading">
            {{ registerForm.loading ? '注册中...' : '注册' }}
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';
import { login, register, sendVerificationCode } from '../api/auth';

export default defineComponent({
  name: 'AuthModal',
  props: {
    show: {
      type: Boolean,
      required: true
    }
  },
  emits: ['close', 'login-success', 'register-success'],
  setup(props, { emit }) {
    const activeTab = ref('login');
    
    const loginForm = reactive({
      email: '',
      password: '',
      loading: false,
      error: ''
    });
    
    const registerForm = reactive({
      email: '',
      password: '',
      confirmPassword: '',
      nickname: '',
      verificationCode: '',
      codeSent: false,
      countdown: 0,
      loading: false,
      error: ''
    });
    
    const close = () => {
      emit('close');
    };
    
    const handleLogin = async () => {
      // 重置错误信息
      loginForm.error = '';
      loginForm.loading = true;
      
      try {
        // 调用登录接口
        const response = await login({
          email: loginForm.email,
          password: loginForm.password
        });
        
        if (response.success) {
          // 登录成功
          localStorage.setItem('isLoggedIn', 'true');
          localStorage.setItem('userEmail', loginForm.email);
          if (response.token) {
            localStorage.setItem('token', response.token);
          }
          if (response.user?.nickname) {
            localStorage.setItem('userNickname', response.user.nickname);
          }
          emit('login-success');
          close();
        } else {
          // 登录失败
          loginForm.error = response.message || '登录失败，请稍后重试';
        }
      } catch (error) {
        console.error('登录出错:', error);
        loginForm.error = '登录失败，请稍后重试';
      } finally {
        loginForm.loading = false;
      }
    };
    
    const sendVerificationCode = async () => {
      if (registerForm.email && !registerForm.codeSent) {
        try {
          // 调用发送验证码接口
          const response = await sendVerificationCode({
            email: registerForm.email
          });
          
          if (response.success) {
            // 发送成功，开始倒计时
            registerForm.codeSent = true;
            registerForm.countdown = 60;
            
            const timer = setInterval(() => {
              registerForm.countdown--;
              if (registerForm.countdown <= 0) {
                clearInterval(timer);
                registerForm.codeSent = false;
              }
            }, 1000);
          } else {
            // 发送失败
            alert(response.message || '发送验证码失败，请稍后重试');
          }
        } catch (error) {
          console.error('发送验证码出错:', error);
          alert('发送验证码失败，请稍后重试');
        }
      }
    };
    
    const handleRegister = async () => {
      // 验证密码是否一致
      if (registerForm.password !== registerForm.confirmPassword) {
        registerForm.error = '两次输入的密码不一致';
        return;
      }
      
      // 重置错误信息
      registerForm.error = '';
      registerForm.loading = true;
      
      try {
        // 调用注册接口
        const response = await register({
          email: registerForm.email,
          password: registerForm.password,
          nickname: registerForm.nickname,
          verificationCode: registerForm.verificationCode
        });
        
        if (response.success) {
          // 注册成功
          localStorage.setItem('isLoggedIn', 'true');
          localStorage.setItem('userEmail', registerForm.email);
          localStorage.setItem('userNickname', registerForm.nickname);
          if (response.token) {
            localStorage.setItem('token', response.token);
          }
          emit('register-success');
          close();
        } else {
          // 注册失败
          registerForm.error = response.message || '注册失败，请稍后重试';
        }
      } catch (error) {
        console.error('注册出错:', error);
        registerForm.error = '注册失败，请稍后重试';
      } finally {
        registerForm.loading = false;
      }
    };
    
    return {
      activeTab,
      loginForm,
      registerForm,
      close,
      handleLogin,
      sendVerificationCode,
      handleRegister
    };
  }
});
</script>

<style scoped>
.auth-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  width: 400px;
  max-width: 90%;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 1rem;
  border-bottom: 1px solid #eee;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
}

.tabs {
  display: flex;
  width: 100%;
}

.tab {
  padding: 1rem;
  flex: 1;
  text-align: center;
  cursor: pointer;
  font-weight: 500;
  color: #666;
  transition: all 0.3s;
}

.tab.active {
  color: #007acc;
  border-bottom: 2px solid #007acc;
}

.tab-content {
  padding: 1.5rem 1.5rem 2rem;
}

.form-group {
  margin-bottom: 1.5rem;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
  text-align: left;
  font-size: 0.95rem;
}

.form-group input {
  width: 100%;
  padding: 0.75rem 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  transition: border-color 0.3s, box-shadow 0.3s;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
  border-color: #007acc;
  box-shadow: 0 0 0 2px rgba(0, 122, 204, 0.2);
}

.verification-code .code-input-container {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.verification-code input {
  flex: 1;
}

.send-code-btn {
  white-space: nowrap;
  padding: 0.75rem 1rem;
  background-color: #f0f0f0;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  height: 100%;
  font-size: 0.9rem;
}

.send-code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.submit-btn {
  width: 100%;
  padding: 0.85rem;
  background-color: #007acc;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s, transform 0.2s;
  margin-top: 0.5rem;
}

.submit-btn:hover {
  background-color: #0062a3;
  transform: translateY(-1px);
}

.submit-btn:active {
  transform: translateY(0);
}

.submit-btn:disabled {
  background-color: #7fb7d9;
  cursor: not-allowed;
  transform: none;
}

.error-message {
  color: #e74c3c;
  font-size: 0.9rem;
  margin-bottom: 1rem;
  text-align: center;
  padding: 0.5rem;
  background-color: rgba(231, 76, 60, 0.1);
  border-radius: 4px;
}

@media (max-width: 480px) {
  .modal-content {
    width: 95%;
  }
  
  .tab-content {
    padding: 1.5rem 1rem 1.5rem;
  }
  
  .verification-code .code-input-container {
    flex-direction: column;
    gap: 0.5rem;
  }
  
  .send-code-btn {
    width: 100%;
    padding: 0.75rem;
  }
}
</style>